<?php
namespace App\Services;
use App\Models\TestUser;
use App\DTOS\Admin\TestUserSearchDTO;
use App\DTOS\Admin\TestUserInsertDTO;
use App\DTOS\Admin\TestUserUpdateDTO;
// 测试用户
class TestUserService
{
    /**
    * @var  \Illuminate\Database\Eloquent\Builder
    */
    private TestUser $model;

    public function __construct()
    {
        $this->model = new TestUser;
    }

    public function paginate(TestUserSearchDTO $DTO)
    {
        $perPage = $DTO->getLimit();
        $page = $DTO->getPage();
        $model = $this->model;
        /**条件判断**/
        return $model->orderByDesc('id')->paginate($perPage,'*','page',$page);
    }

    /**
    * @param  TestUserInsertDTO $insertDTO
    * @return  int
    */
    public function insert(TestUserInsertDTO $insertDTO){
        $data = $insertDTO->toArray();
        unset($data['page']); unset($data['limit']);
        foreach($data as &$value){
            if (is_array($value)){
                $value= json_encode(array_values($value));
            }
        }
        $data['created_at'] = now();
        return $this->model->insertGetId($data);
    }

    /**
    * @param  int $id
    * @param  TestUserUpdateDTO $updateDTO
    */
    public function updateById($id,TestUserUpdateDTO $updateDTO)
    {
        $data = $updateDTO->toArray();
        unset($data['page']); unset($data['limit']);
        foreach($data as &$value){
            if (is_array($value)){
                $value= json_encode(array_values($value));
            }
        }
        $data['updated_at'] = now();
        $this->model->where('id',$id)->update($data);
    }

    public function deleteById($id)
    {
        $this->model->where('id',$id)->delete();
    }

    public function deleteByIds($ids)
    {
        if (empty($ids)) return;
        $this->model->whereIn('id',$ids)->delete();
    }
    public function getById($id)
    {
        return $this->model->where('id',$id)->first();
    }
}
